﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;

namespace Tornado
{
    public class MainProcesser
    {
        volatile SignalProcesser[] processers = new SignalProcesser[]
        {
            new SignalPowerpoint(),
            new SignalProcesserMouse(),
            new SignalProcessPower(),
            new SignalProcessZoom()
        };
        //volatile 
        volatile SignalReceiver receiver = new SignalReceiver();

        Thread receiveRunner;

        public bool isReceiveRunning = false;

        public void Run()
        {

            ThreadStart thStart = new ThreadStart(_run);
            receiveRunner = new Thread(thStart, 0);
            receiveRunner.Name = "MainProcesser";
            receiveRunner.Start();
            isReceiveRunning = true;

        }
        private void _run()
        {
            SignalPacket packet;
            receiver.BeginReceive();
            //Receive process
            while (true)
            {
                try
                {
                    packet = receiver.NextCommand();
                }
                catch //User stop
                {
                    return;
                }
                foreach (var p in processers)
                {
                    if ((byte)p.Code == packet.Code)
                    {
                        p.Process(ref packet);
                        break;
                    }
                }
            }
        }

        public void Stop()
        {
            receiver.StopReceive();
            isReceiveRunning = false;
        }
    }
}
